package admin

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"strings"
)

type AddAuthority struct {
	Id       string `json:"id"`
	Category int64  `json:"category"`
	Name     string `json:"name"`
	Code     string `json:"code"`
}

type AuthorityListParam struct {
	PerPage int `json:"perPage"`
	CurPage int `json:"curPage"`
}

type Authority struct {
	Ctx iris.Context
}

func (c *Authority) OptionsCreate() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Authority) PostCreate() interface{} {
	addAuthority := AddAuthority{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &addAuthority)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if addAuthority.Category <= 0 {
		return utils.CommonRes(1000, "请选择权限分类", "")
	}
	if len(addAuthority.Name) < 0 {
		return utils.CommonRes(1000, "请输入权限名称", "")
	}
	if len(addAuthority.Code) <= 0 {
		return utils.CommonRes(1000, "请输入权限识别码", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	authority := new(models.Authority)
	authority.CategoryId = addAuthority.Category
	authority.Name = addAuthority.Name
	authority.Code = addAuthority.Code
	_, err = db.InsertOne(authority)

	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("操作失败:%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func (c *Authority) OptionsEdit() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Authority) PostEdit() interface{} {
	addAuthority := AddAuthority{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &addAuthority)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(addAuthority.Id) <= 0 {
		return utils.CommonRes(1000, "请提供权限id", "")
	}
	if len(addAuthority.Name) <= 0 {
		return utils.CommonRes(1000, "请输入权限名称", "")
	}
	if addAuthority.Category <= 0 {
		return utils.CommonRes(1000, "请选择权限分类", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	updateData := map[string]interface{}{
		"category_id": addAuthority.Category,
		"name":    addAuthority.Name,
		"code": addAuthority.Code,
	}

	_, err = db.Table(new(models.Authority)).ID(addAuthority.Id).Update(updateData)
	if err != nil {
		return utils.CommonRes(1000, "操作失败", "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func (c *Authority) OptionsAll() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Authority) PostAll() interface{} {
	editParam := utils.EditParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &editParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	authorityCategoryList := make([]models.AuthorityCategory, 0)
	err = db.Find(&authorityCategoryList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取权限分类列表:%s", err.Error()), "")
	}

	role := new(models.Role)
	ok, err := db.Id(editParam.Id).Get(role)
	if len(editParam.Id) > 0 {
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("角色信息获取失败:%s", err.Error()), "")
		}
		if !ok {
			return utils.CommonRes(1000, "角色信息获取失败", "")
		}
	}

	for i, item := range authorityCategoryList {
		authorityList := make([]models.Authority, 0)
		db.Where("category_id = ?", item.Id).Find(&authorityList)
		if len(editParam.Id) > 0 {
			for j, authority := range authorityList {
				ok := strings.Contains(role.Authorities, authority.Code)
				if ok {
					authorityList[j].IsChecked = 1
				} else {
					authorityList[j].IsChecked = 0
				}
			}
		}
		authorityCategoryList[i].AuthorityList = authorityList
	}

	return utils.CommonRes(20000, "成功获取所有权限列表", authorityCategoryList)
}

func (c *Authority) OptionsList() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Authority) PostList() interface{} {
	authorityListParam := AuthorityListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &authorityListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	start := (authorityListParam.CurPage - 1) * authorityListParam.PerPage
	authorityList := make([]models.AuthorityObj, 0)
	err = db.Table("authority").Alias("a").
		Join("INNER", []string{"authority_category", "ac"}, "a.category_id = ac.id").
		Select("a.*,ac.*").Limit(authorityListParam.PerPage, start).Find(&authorityList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取权限列表:%s", err.Error()), "")
	}

	total, err := db.Where("id > ?", 0).Count(new(models.Authority))
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取权限列表:%s", err.Error()), "")
	}

	for i, item := range authorityList {
		authorityList[i].AuthorityCategoryCreated = item.Authority.Created.Format("2006-01-02 15:04")
	}

	data := map[string]interface{}{
		"total": total,
		"list":  authorityList,
	}

	return utils.CommonRes(20000, "成功获取权限列表", data)
}

func (c *Authority) OptionsDetail() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Authority) PostDetail() interface{} {
	editParam := utils.EditParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &editParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}
	if len(editParam.Id) <= 0 {
		return utils.CommonRes(1000, "参数不完整", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	authority := new(models.Authority)
	ok, err := db.ID(editParam.Id).Get(authority)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("信息获取失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "信息获取失败", "")
	}

	return utils.CommonRes(20000, "信息获取成功", authority)
}

func (c *Authority) OptionsDel() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Authority) PostDel() interface{} {
	delParam := utils.DelParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &delParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(delParam.Ids) <= 0 {
		return utils.CommonRes(1000, "请提供要删除项的id", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	ids := strings.Split(delParam.Ids, ",")
	for _, id := range ids {
		authority := new(models.Authority)
		db.ID(id).Get(authority)
		db.ID(id).Delete(authority)
	}

	return utils.CommonRes(20000, "操作成功", "")
}
